package com.boxin.ims.modules.wechat.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import com.boxin.ims.modules.wechat.entity.dic.Address;
import com.thinkgem.jeesite.common.utils.StringUtils;

public class BaiduMap {
	
	
	
	//private static String ak = "5ef2641d89438a6e708db122820cf1d2";  
	private static String ak = "9E5C17451f498e58baa96785e4bc6a0f";  
    
    public static Map<String, String> testPost(String x, String y) throws IOException {  
        URL url = new URL("http://api.map.baidu.com/geocoder?" + ak + "=您的密钥" +   
                "&callback=renderReverse&location=" + x  
                        + "," + y + "&output=json");  
        URLConnection connection = url.openConnection();  
        /** 
         * 然后把连接设为输出模式。URLConnection通常作为输入来使用，比如下载一个Web页。 
         * 通过把URLConnection设为输出，你可以把数据向你个Web页传送。下面是如何做： 
         */  
        connection.setDoOutput(true);  
        OutputStreamWriter out = new OutputStreamWriter(connection  
                .getOutputStream(), "utf-8");  
//        remember to clean up  
        out.flush();  
        out.close();  
//        一旦发送成功，用以下方法就可以得到服务器的回应：  
        String res;  
        InputStream l_urlStream;  
        l_urlStream = connection.getInputStream();  
        BufferedReader in = new BufferedReader(new InputStreamReader(  
                l_urlStream,"UTF-8"));  
        StringBuilder sb = new StringBuilder("");  
        while ((res = in.readLine()) != null) {  
            sb.append(res.trim());  
        }  
        String str = sb.toString();  
        System.out.println(str);  
        JSONObject json = JSONObject.fromObject(str);
        String result = json.get("result").toString();
        json = JSONObject.fromObject(result);
        String addressComponent = json.get("addressComponent").toString();
        json = JSONObject.fromObject(addressComponent);
        
        
        Map<String,String> map = null;  
        if(StringUtils.isNotEmpty(str)) {  
        	//地址
            int addStart = str.indexOf("formatted_address\":");  
            int addEnd = str.indexOf("\",\"business");  
            if(addStart > 0 && addEnd > 0) {  
                String address = str.substring(addStart+20, addEnd);  
                map = new HashMap<String,String>();  
                map.put("address", address);  
                return map;       
            }  
            
        }  
          
        return null;  
          
    }  
    
    
    
    public static Address getAddressInfoByXY(String x, String y)  throws IOException{
    	 URL url = new URL("http://api.map.baidu.com/geocoder?" + ak + "=您的密钥" +   
                 "&callback=renderReverse&location=" + x  
                         + "," + y + "&output=json");  
         URLConnection connection = url.openConnection();  
         /** 
          * 然后把连接设为输出模式。URLConnection通常作为输入来使用，比如下载一个Web页。 
          * 通过把URLConnection设为输出，你可以把数据向你个Web页传送。下面是如何做： 
          */  
         connection.setDoOutput(true);  
         OutputStreamWriter out = new OutputStreamWriter(connection  
                 .getOutputStream(), "utf-8");  
//         remember to clean up  
         out.flush();  
         out.close();  
//         一旦发送成功，用以下方法就可以得到服务器的回应：  
         String res;  
         InputStream l_urlStream;  
         l_urlStream = connection.getInputStream();  
         BufferedReader in = new BufferedReader(new InputStreamReader(  
                 l_urlStream,"UTF-8"));  
         StringBuilder sb = new StringBuilder("");  
         while ((res = in.readLine()) != null) {  
             sb.append(res.trim());  
         }  
         
         String str = sb.toString();  
         System.out.println(str);  
         
         
         
         Address address = new Address();
         JSONObject json = JSONObject.fromObject(str);
         String result = json.get("result").toString();
         if(StringUtils.isNotEmpty(result)){
        	 json = JSONObject.fromObject(result);
        	 
        	 String addressComponent = json.get("addressComponent").toString();
        	 json = JSONObject.fromObject(addressComponent);
         }
         
         
         if(json.get("province") != null){
        	 String province = json.get("province").toString();
        	 province = province.replace("省", "");
        	 address.setProvince(province);
         }
         
         
         if(json.get("city") != null){
        	 String city = json.get("city").toString();
        	 city = city.replace("市", "");
        	 address.setCity(city);
         }
         
        
         
         if(json.get("district")  != null){
        	 String district = json.get("district").toString();
        	 address.setDistrict(district);
         }
         
         
    	
         
    	return address;
    }
	
	public static void main(String[] args) {
		try {
//			Map<String, String> json = BaiduMap.testPost("30.542938", "114.064022");  
//			System.out.println("address :" + json.get("address"));  
//			System.out.println("addressComponent :" + json.get("city"));  
			
			Address address = 	BaiduMap.getAddressInfoByXY("30.542938", "114.064022");
			
			System.out.println(address.getProvince()+"\t"+address.getCity()+"\t"+address.getDistrict());
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	
	
	

}
